package com.qfedu.springmvc02.controller;


import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MultipartFilter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;

@Controller
@SessionAttributes({"list"})
public class FileController {


    @RequestMapping("/upload")
    public String upload(MultipartFile file, String name, Model model, HttpServletRequest request) throws IOException {
        //获取web服务器中部署项目在磁盘上的真实路径
        String realPath = request.getServletContext().getRealPath("/");
        //获取当前路径下的upload文件夹
        File upload = new File(realPath, "upload");
        //判断  如果文件夹不存在   就创建文件夹
        if (!upload.exists()) {
            upload.mkdirs();
        }
        if (Objects.nonNull(file)) {
            //获取传过来文件的名字
            String filename = file.getOriginalFilename();
            // 第一个值 位置，第二个 名字
            file.transferTo(new File(upload, filename));
            String[] list = upload.list();
            model.addAttribute("list", list);
            return "welcome";
        }else {
            String[] list = upload.list();
            model.addAttribute("list",list);
            return "welcome";
        }
    }



    //多文件上传
    @RequestMapping("upload2")
    public String upload2(MultipartFile [] files,HttpServletRequest request,Model model) throws IOException {
        //获取服务器部署在本地的地址
        String realPath = request.getServletContext().getRealPath("/");
        //获取 当前路径下的upload文件夹
        File upload = new File(realPath, "upload");
        //如果没有 就创建
        if (!upload.exists()){
            upload.mkdirs();
        }
        //循环前台传过来的数组
        for (MultipartFile file : files) {
            //获取前台传过来的的名字
            String filename = file.getOriginalFilename();
            //判断是否为空，不为空继续执行
            if (Objects.nonNull(filename)&& filename !=""){
                //获取名字.(包括.)以后的字串
            String substring = filename.substring(filename.indexOf("."));
            //判断 是否是以下几个格式
            if(substring.equalsIgnoreCase(".jpg") || substring.equalsIgnoreCase(".gif")
              || substring.equalsIgnoreCase(".png") || substring.equalsIgnoreCase(".bmp")
            ){
                //定义uuid
                String uuid = UUID.randomUUID().toString();
                //把uuid里面的- 替换成 "" 在＋刚才截取的字串重新赋值给uuid
                uuid = uuid.replace("-", "") + substring;
                //写入文件夹中，第一个值是路径，第二个是文件名
                file.transferTo(new File(upload,uuid));
                //把文件夹下的文件名放到数组中
                String[] list = upload.list();
                model.addAttribute("list",list);
            }else {
                //格式不对
                model.addAttribute("error","必须上传图片");
                return "welcome";
            }
            }else {
                //如果传过来的为空， 直接跳过循环
                continue;
            }
        }
        return "welcome";
    }

    //下载
    @RequestMapping("download")
    public void download(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println(filename);
        //设置响应格式   让浏览器使用attachment附件的格式下载
        response.setHeader("content-disposition","attachment;filename=" + filename);

        //定义输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //获取下载文件所在的真实地址
        String realPath = request.getServletContext().getRealPath("/upload");
        //获取你要下载的文件对象
        File file = new File(realPath, filename);
        //读取文件 到字节数组中
        byte[] bytes = FileUtils.readFileToByteArray(file);
        //把字节数组写到输出流
        outputStream.write(bytes);
        outputStream.close();
    }

}
